package com.ruan.filter;

import com.ruan.entity.LoginUser;
import com.ruan.utils.Auth0JwtUtils;
import com.ruan.utils.LongAuth0JwtUtils;
import com.ruan.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

/**
 * @ClassName:JwtAuthenticationTokenFilter
 * @Author:阮昇
 * @Description:
 * @Datetime: 2023/9/20 15:02
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String authorizationHeader = request.getHeader("Authorization");
        String token = "";
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 获取Bearer后的token值
            token = authorizationHeader.substring(7);
        }
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //判断token是否正确
        if (!Auth0JwtUtils.verify(token)){
            // 返回状态码给前端
            throw new RuntimeException("无效token");
        }
        //解析token
        String userid = "";
        try {
            userid = Auth0JwtUtils.getClaims(token).get("userId").asString();
        } catch (Exception e) {
            // 返回状态码给前端
            throw new RuntimeException("无效token");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = (LoginUser) RedisUtil.get(redisKey);
        if (Objects.isNull(loginUser)) {
            // 返回状态码给前端
            throw new RuntimeException("用户未登陆");
        }
        if (LongAuth0JwtUtils.isExpired(loginUser.getLongToken())){
            RedisUtil.del("login:"+loginUser.getUser().getId());
            // 返回状态码给前端
            throw new RuntimeException("登陆过期请重新登录");
        }
        if (Auth0JwtUtils.isExpired(token)){
            HashMap<String,Object> userMap = new HashMap<>();
            userMap.put("userId",loginUser.getUser().getId().toString());
            String newToken = Auth0JwtUtils.sign(userMap);
            String newLongToken = LongAuth0JwtUtils.sign(userMap);
            loginUser.setToken(newToken);
            loginUser.setLongToken(newLongToken);
            //authenticate存入redis
            RedisUtil.set("login:"+loginUser.getUser().getId(),loginUser);
            response.setHeader("newtoken",newToken);
            response.setHeader("Access-Control-Expose-Headers", "newtoken");
        }
        //存入SecurityContextHolder
        //TODO获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
